// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require("base");
	var leftMenu = require("../leftMenu/leftMenu");
	var topMenu = require("../topMenu/topMenu");
	var footer = require("../footer/footer_main");
	var router = require("../hash/pageRouter");
	var dialog = require("dialog");
	var validate = require("validate");
	var tools = require("tools");
	var css_dialog = require("css_dialog");
	var databind = require("databind");
	var html_verify_list = require("./html_verify_list.html");
	var html_receivables_detail = require("./html_receivables_detail.html");
	var html_loan_detail = require("./html_loan_detail.html");
	var html_expense_detail = require("./html_expense_detail.html");
	var storage = window.sessionStorage;
	var constant = require("constant");
	var verifyList = [];
	var writeoffId;
	var billReceivableId;
	var disbursementId;
	var type;
	var s;
	var pageIndex = 1,
		pageSize = 10,
		totalPageCount = 1,
		totalRecordCount = 0; //分页初始化
	var myData = {};
	var oData = {};
	var init = function() {
//		type = base.getUrlParam("type");
//		disbursementId = base.getUrlParam("disbursementId");
		oData = tools.GetRequest(oData, null);
		
		type = storage.getItem("type");
		disbursementId = storage.getItem("disbursementId");
		
		footer.init();
		$("#footer").removeClass("none");
		leftMenu.init(5);
		topMenu.init(1);
		router.init();
		$(".table-section").removeClass("none");
		$(".footer").removeClass("none");
		$(".receiptVerify").parent().parent().parent().addClass("leftMenu-open");
		$(".receiptVerify").parent().addClass("leftMenu-active");
		tools.requireInput($("#verifyRecepit"));
		inquireBlankInfoPagelist();
		
		$(".disbursementNameDiv").flexbox(CONFIG.ApiPath + CONFIG.ApiVersion + "/inquireEnterpriseListForSelector.json?sessionUuid=" + base.getData("sid") + "&appKey=" + base.getData("appKey"), {
			width: 178,
    		paging: 5,
    		watermark: '请选择付款企业',
    		onSelect: function(){
    			$("#verifyRecepit input[name=drawee]").val($(".disbursementNameDiv .ffb-sel").attr("val"));
    			$("#verifyRecepit input[name=disbursementName]").val($(".disbursementNameDiv .ffb-sel").attr("val"));
    			inquireEnterpriseBlankInfo($(".disbursementNameDiv .ffb-sel").attr("id"));
    			if ($.trim($("input[name=drawee]").val()) == "") {
					$("#addReceptBtn").hide();
				} else {
					$("#addReceptBtn").show();
				}
    		}
		});
		
		if (type == "compile") {
			$("#verifyRecepit").attr("action", "createBillReceivable");
			$("#verifyRecepit").append("<input type='hidden' name='billType' value='1' />");
			$("#addReceptBtn").hide();
			$("input[name=writeoffAmount]").removeAttr("readonly").attr("name", "amount");
			$("input[name=writeoffDateTime]").parent().html("");
		} else if (type == "verify") {
			$("#addReceptBtn").show();
			$("#addReceptBtn").removeClass("none");
			billReceivableId = base.getUrlParam("billReceivableId");
			inquireBillReceivableDetail(billReceivableId);
			databind.disableInput($("#verifyRecepit"));
			$("input[name=writeoffAmount]").removeAttr("disabled");
			$("input[name=writeoffDateTime]").removeAttr("readonly").removeAttr("disabled");
			$("textarea[name=writeoffRemark]").removeAttr("readonly").removeAttr("disabled");
			$("#undefined_input").attr("disabled", "disabled");
			$("#undefined_arrow").css("pointer-events", "none");
			$(".verifyIntro").remove();
		} else if (type == "detail") {
			billReceivableId = base.getUrlParam("billReceivableId");
			inquireBillReceivableDetail(billReceivableId);
			databind.disableInput($("#verifyRecepit"));
			$("#verifyRecepitSubmit").hide();
			$(".verifyIntro").hide();
			$("#addReceptBtn").remove();
		} else if (type == "normal") {
			
		} else if (type == "singleVerify") {
//			s = base.getUrlParam("str");
			s = storage.getItem("str");
			s = decodeURI(decodeURI(s));
//			var di = base.getUrlParam("disbursementId");
//			var dn = decodeURI(base.getUrlParam("disbursementName"));
			
			var di = storage.getItem("disbursementId");
			var dn = decodeURI(decodeURI(storage.getItem("disbursementName")));
			
			$("#verifyRecepit input[name=drawee]").val(dn);
			$("#verifyRecepit input[name=disbursementName]").val(dn);
			$("#verifyRecepit #undefined_input").val(dn);
			inquireEnterpriseBlankInfo(di);
			
			$("#addReceptBtn").remove();
			$("#verifyListBody").removeClass("none");
			$("#verifyListBody").append(s);	
			$("#verifyListBody tr").removeClass("none");
			var totalAmount = 0;
			$.each($("input[name=verifiAmount]"), function() {
				var $this = $(this);
				totalAmount += $this.val()*1;
			});
			
			$("input[name=writeoffAmount]").val(totalAmount);
			
			inquireLendUnitInfoDetail(disbursementId);
		}
		
		initEvent();
	};
	var initEvent = function() {
		//若未登录，则返回登陆页面
		if (base.getData("sid") == null || base.getData("sid") == "" || base.getData("sid") == undefined) {
			location.href = "../login/login.html";
		}
		
		if ($.trim($("input[name=drawee]").val()) == "") {
			$("#addReceptBtn").hide();
		} else {
			$("#addReceptBtn").show();
		}
			
		$("#verifyRecepit").on("change", "#undefined_input", function(){
			$("#verifyRecepit input[name=drawee]").val($(this).val());
			$("#verifyRecepit input[name=disbursementName]").val($(this).val());
			if ($.trim($("input[name=drawee]").val()) == "") {
				$("#addReceptBtn").hide();
			} else {
				$("#addReceptBtn").show();
			}
		});
		
		tools.clearNoNumAll($("#verifyRecepit"));
		
		$("#verifyRecepit").on("change", "input[name=verifiAmount]", function(){
			
			if (($(this).parents("tr").attr("statementSource") == 'RECEIVABLES' || $(this).parents("tr").attr("statementSource") == 'RECEIVABLES_WAREHOUSE') && $(this).val()*1 > $(this).attr("amount")*1) {
				base.alert(3, "核销金额不能大于应收金额！");
				$(this).val($(this).attr("amount"));
				return false;
			}
			
			var totalAmount = 0;
			$.each($("input[name=verifiAmount]"), function() {
				var $this = $(this);
				totalAmount += $this.val()*1;
			});
			
			$("input[name=writeoffAmount]").val(totalAmount);
		});
		
		$("#verifyRecepit select[name=disbursementName]").unbind("change").change(function(){
			inquireEnterpriseBlankInfo($("#verifyRecepit select[name=disbursementName] option:selected").attr("enterpriseId"));
		});

		$("#leftMenu9").on("click", ".claimManage", function() {
			router.route("claimManage/claimManage.html");
		});

		$("#leftMenu9").on("click", ".insurance1", function() {
			location.href = "../insuranceManage/insuranceManage.html";
		});

		$("#leftMenu9").on("click", ".insurance2", function() {
			location.href = "../insuranceManage/insuranceManage.html";
		});

		$("#leftMenu9").on("click", ".insurance3", function() {
			location.href = "../insuranceManage/insuranceManage.html";
		});

		$("#leftMenu9").on("click", ".insurance4", function() {
			location.href = "../insuranceManage/insuranceManage.html";
		});
		
		$("#verifyRecepit select[name=accountInfoId]").on("change", function(){
			var $this = $(this);
			$("#verifyRecepit .receiptBank").val($this.find("option:selected").attr("accountbank"));
			$("#verifyRecepit .receiptName").val($this.find("option:selected").attr("accountBankName"));
			$("#verifyRecepit input[name=receiptName]").val($this.find("option:selected").attr("accountBankName"));
			$("#verifyRecepit .receiptCreditCard").val($this.find("option:selected").attr("accountBankCard"));
		});
		
		$("#verifyRecepit").on("click", ".statementNumber", function() {
			var statementSourceId = $(this).attr("statementSourceId");
			var statementSource = $(this).attr("statementSource");
			switch (statementSource) {
				case "RECEIVABLES":
					$("#popdialog").html(html_receivables_detail);
					dialog.showDialog($("#receivable_detail_dialog"));
					databind.fillInput($("#receivable_detail_dialog"), {
						action: "inquireReceivablesDetail.json?receivablesId=" + statementSourceId
					});
					databind.disableInput($("#receivable_detail_dialog"));
					$(".sure_yes").unbind("click").click(function() {
						dialog.hideDialog($("#receivable_detail_dialog"));
					});

					$(".sure_no").unbind("click").click(function() {
						router.route("financing/receivableNoticeDetail.html?receivablesId=" + statementSourceId);
						dialog.hideDialog($("#receivable_detail_dialog"));
					});
					break;
				case "ABNORMAL_EXPENSE":
					$("#popdialog").html(html_expense_detail);
					dialog.showDialog($("#exception_detail_dialog"));
					tools.inquireCommonSelectorList(9, $(".expenseType"));
					databind.fillInput($("#exception_detail_dialog"), {
						action: "inquireAbnormalExpenseDetail.json?abnormalExpenseId=" + statementSourceId
					});
					databind.disableInput($("#exception_detail_dialog"));
					$(".sure_yes").unbind("click").click(function() {
						dialog.hideDialog($("#exception_detail_dialog"));
					});
					$(".sure_no").unbind("click").click(function() {
						var abnormalId = $("#abnormalId").val();
						dialog.hideDialog($("#exception_detail_dialog"));
						storage.setItem("abnormalId", abnormalId);
						location.href = "../exception/exceptionManage.html#exception/exceptionDetailInfo";
					});
					break;
				case "LOAN_NOTICE":
					$("#popdialog").html(html_loan_detail);
					dialog.showDialog($("#loan_detail_dialog"));
					databind.fillInput($("#loan_detail_dialog"), {
						action: "inquireLoanNoticeDetail.json?loanNoticeId=" + statementSourceId
					});
					databind.disableInput($("#loan_detail_dialog"));
					$(".sure_yes").unbind("click").click(function() {
						dialog.hideDialog($("#loan_detail_dialog"));
					});

					$(".sure_no").unbind("click").click(function() {
						router.route("financing/loanNotice.html?loanNoticeId=" + statementSourceId);
						dialog.hideDialog($("#loan_detail_dialog"));
					});
					break;
				case "INSURANCE":
					router.route("insuranceManage/insuranceDetail.html?insuranceId=" + statementSourceId);
					break;
				case "FINANCE_AUDIT":
					router.route("main/financeApproveDetail.html.html?financeAuditId=" + statementSourceId);
					break;
				default:
					break;
			}
		});

		$("#addReceptBtn").unbind("click").click(function() {
			$("#popdialog").html(html_verify_list);
			$(".searchBox1").removeClass("none");
			dialog.showDialog($("#verify_list_dialog"));
			oData.disbursementName = $("#verifyRecepit input[name=disbursementName]").val();
			tools.loadList("inquireReceiptMoneyStatementPageList.json", $("#htmlVerifyListTable"), $("#htmlVerifyListTpl"), oData, function() {
				$("#verify_list_dialog .sure_yes").unbind("click").click(function() {
					$.each($("#verify_list_dialog .moneyStatementId:checked"), function() {
						var $this = $(this);
						var str = '<tr moneystatementId="' + $this.parents("tr").attr("moneystatementId") + '">' + $(this).parents("tr").html() + '<td><input name="verifiAmount" onkeyup="this.value=value.replace(/[^\\d{1,}\\.\\d{1,}|\\d{1,}]/g, \'\')" type="text" value="' + $this.parents("tr").attr("balanceAmount") + '" /></td><td><a class="remove">删除</a></td></tr>';
						if (verifyList.indexOf($this.parents("tr").attr("moneystatementId")) < 0) {
							$("#verifyListBody").removeClass("none");
							verifyList.push($this.parents("tr").attr("moneystatementId"));
							$("#verifyListBody").append(str);
							$("#verifyListBody").find("tr td input[type=checkbox]").parent().remove();
						}
					});
					
					var totalAmount = 0;
					$.each($("input[name=verifiAmount]"), function() {
						var $this = $(this);
						totalAmount += $this.val()*1;
					});
					
					$("input[name=writeoffAmount]").val(totalAmount);
					
					dialog.hideDialog($("#verify_list_dialog"));
					$("#verifyListBody .remove").unbind("click").click(function() {
						var m = $(this).parents("tr").attr("moneyStatementId");
						$.each(verifyList, function(i, v) {
							if (m == v) {
								verifyList.splice($.inArray(v, verifyList), 1);
							}
						});
						$(this).parents("tr").remove();
						if ($("#verifyListBody tr").length <= 1) {
							$("#verifyListBody").addClass("none");
						};
						
						var totalAmount = 0;
						$.each($("input[name=verifiAmount]"), function() {
							var $this = $(this);
							totalAmount += $this.val()*1;
						});
						
						$("input[name=writeoffAmount]").val(totalAmount);
					});
				});
				
				$("input[name=verifiAmount]").on("change", function(){
					var totalAmount = 0;
					$.each($("input[name=verifiAmount]"), function() {
						var $this = $(this);
						totalAmount += $this.val()*1;
					});
					
					$("input[name=writeoffAmount]").val(totalAmount);
				});

				$("#verify_list_dialog .sure_no").unbind("click").click(function() {
					dialog.hideDialog($("#verify_list_dialog"));
				});

				$("#verifySearchButton1").unbind("click").click(function() {
					oData.statementBeginDate = $.trim($(".searchBox1 .statementBeginDate").val());
					oData.statementEndDate = $.trim($(".searchBox1 .statementEndDate").val());
					oData.financeNumber = $.trim($(".searchBox1 .financeNumber").val());
					oData.disbursementName = $("#verifyRecepit input[name=disbursementName]").val();
					oData.minSourceAmount = $.trim($(".searchBox1 .minSourceAmount").val());
					oData.maxSourceAmount = $.trim($(".searchBox1 .maxSourceAmount").val());
					oData.statementNumber = $.trim($(".searchBox1 .statementNumber").val());

					tools.loadList("inquireReceiptMoneyStatementPageList.json", $("#htmlVerifyListTable"), $("#htmlVerifyListTpl"), oData, function() {});
				});
			});

		});
		
		if ($.trim($("input[name=disbursementName]").val()) == "") {
			$("#addReceptBtn").hide();
		} else {
			$("#addReceptBtn").show();
		}

		$("#verifyRecepitSubmit").unbind("click").click(function() {
			if ($("#verifyRecepit input[name=balance]").val() != "" && $("#verifyRecepit input[name=writeoffAmount]").val() != null && $("#verifyRecepit input[name=writeoffAmount]").val() != "" && $("#verifyRecepit input[name=balance]").val()*1 < $("#verifyRecepit input[name=writeoffAmount]").val()*1) {
				base.alert(2, "余额不足，不能核销!");
				return;
			}
			databind.submitDom($("#verifyRecepit"), function() {
				base.alert(1, "提交成功！");
				location.href = "../moneyStatementManage/receiptManage.html?1=1"+tools.urlEncode(oData, null);
			});
		});
		
		$("#verifyRecepit").on("click", ".deleteLoanIntro", function() {
			$(this).parent().remove();
			var fileUuids = [];
			$.each($(".showloanIntroDiv"), function() {
				var $this = $(this);
				fileUuids.push($this.find("a").attr("fileUuid"))
			});
			$(".fileUuids").val(fileUuids);
		});
		
		//点击上传附件
		$("#verifyRecepit").on("change", "#verifyIntro", function() {
			uploadFile();
		});
	};
	
	//上传文件
	var uploadFile = function() {
		if ($("#loanIntro").val() != "") {
			$.ajaxFileUpload({
				url: "/finance/api/v1.0/uploadFile.json", //你处理上传文件的服务端
				secureuri: false,
				fileElementId: 'verifyIntro',
				dataType: 'json',
				success: function(data) {
					var str = '<div class="showloanIntroDiv"><a target="_blank" class="mas showloanIntro" fileUuid="' + data.data[0].fileUuid + '" href="/finance/api/v1.0/downloadFile.file?fileUuid=' + data.data[0].fileUuid + '">' + data.data[0].fileName + '</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="deleteLoanIntro">x</a></div>'
					$(".verifyIntro").before(str);
					
					var fileUuids = [];
					$.each($(".showloanIntroDiv"), function() {
						var $this = $(this);
						fileUuids.push($this.find("a").attr("fileUuid"))
					});
					$(".fileUuids").val(fileUuids);
				},
				complete: function(xml) {
					$("#loanIntro").change(function() {
						uploadFile();
					});
				},
				error: function(data, status, e) {
					if (data.msg == null) {
						base.alert(2, "文件太大无法上传");
					} else {
						base.alert(2, data.msg);
					}
				}
			});
		} else {
			base.alert(3, "请选择文件！");
		}
	};
	
	var inquireBillReceivableDetail = function(billReceivableId) {
		base.fnAjax({
			action: "inquireBillReceivableDetail.json",
			oData: {
				billReceivableId: billReceivableId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					databind.fillForm($("#verifyRecepit"), data.datas[0]);
					$("#undefined_input").val(data.datas[0].drawee);
					
					if ($.trim($("input[name=drawee]").val()) == "") {
						$("#addReceptBtn").hide();
					} else {
						$("#addReceptBtn").show();
					}
					
					if (type == "detail") {
						var tpl = $("#verifyListTpl").html();
						var html = juicer(tpl, data);
						$("#verifyListBody").html(html);
						$("#verifyListBody").removeClass("none");
						$(".verifyIntro").remove();
						$("#hide").remove();
						databind.disableInput($("#verifyRecepit"));
						$("#verifyRecepitSubmit").html("返回").attr({
							"id": ""
						}).addClass("goBack").unbind("click").click(function() {
							history.go(-1);
						});
					} else if (type == "verify") {
						$(".dataLine").removeClass("none");
					}
					
					$.each(data.datas[0].fileUuid.split(','), function() {
						if (this != "") {
							var str = '<div class="showloanIntroDiv"><a target="_blank" class="mas showloanIntro" fileUuid="' + this + '" href="/finance/api/v1.0/downloadFile.file?fileUuid=' + this + '">' + tools.inquireFile(this) + '</a></div>';
							$("#verifyRecepit .loan_info4").append(str);
						}
					});
				} else {
					base.alert(2, data.message);
				}
			}
		});
	};

	var inquireSystemBlankInfo = function() {
		base.fnAjax({
			action: "inquireSystemBlankInfo.json", //接口名称
			oData: {}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					$("#verifyRecepit .receiptBank").val(data.datas[0].depositBank);
					$("#verifyRecepit .receiptName").val(data.datas[0].accountHolder);
					$("#verifyRecepit .receiptCreditCard").val(data.datas[0].creditCard);
				}
			}
		});
	};
	
	var inquireLendUnitInfoDetail = function(lendUnitId) {
		base.fnAjax({
			action: "inquireLendUnitInfoDetail.json", //接口名称
			oData: {
				lendUnitId: lendUnitId
			}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					$("input[name=disbursementBank]").val(data.datas[0].lendUnitBank);
					$("input[name=disbursementCreditCard]").val(data.datas[0].lendUnitBankCard);
					$("#undefined_hidden").val(data.datas[0].lendUnitName);
				}
			}
		});
	};
	
	var inquireBlankInfoPagelist = function() {
		base.fnAjax({
			action: "inquireBlankInfoPagelist.json", //接口名称
			oData: {
				pageSize: 1000
			}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					$.each(data.datas, function() {
						var str = "<option accountBankName='"+ this.accountBankName +"' accountBankCard='"+ this.accountBankCard +"' accountBank='"+ this.accountBank +"' value='"+ this.accountInfoId +"'>" + this.accountBank + "(" + this.accountBankName + ")" + "</option>";
						$("select[name=accountInfoId]").append(str);
					});
					
					$("#verifyRecepit .receiptBank").val($("select[name=accountInfoId]").find("option:selected").attr("accountbank"));
					$("#verifyRecepit .receiptName").val($("select[name=accountInfoId]").find("option:selected").attr("accountBankName"));
					$("#verifyRecepit input[name=receiptName]").val($("select[name=accountInfoId]").find("option:selected").attr("accountBankName"));
					$("#verifyRecepit .receiptCreditCard").val($("select[name=accountInfoId]").find("option:selected").attr("accountBankCard"));
					
				}
			}
		});
	};
	
	var inquireEnterpriseBlankInfo = function(enterpriseId) {
		base.fnAjax({
			action: "inquireEnterpriseDetail.json", //接口名称
			oData: {
				enterpriseId: enterpriseId
			}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					$("#verifyRecepit input[name=disbursementBank]").val(data.datas[0].depositBank);
					$("#verifyRecepit input[name=disbursementCreditCard]").val(data.datas[0].creditCard);
				}
			}
		});
	};

	return {
		init: init
	};
});